package cn.autumnorange.app.gateway.security;

import cn.autumnorange.app.common.rpc.exception.JsonException;
import cn.autumnorange.app.common.rpc.exception.JsonExceptionImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.UrlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功重定向到登录成功接口
 */
public class GateWayDefaultRedirectStrategy implements RedirectStrategy {
  protected final Log logger = LogFactory.getLog(this.getClass());
  private boolean contextRelative;
  private JsonException jsonException = new JsonExceptionImpl();

  public GateWayDefaultRedirectStrategy() {}

  public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)
      throws IOException {
    String redirectUrl = this.calculateRedirectUrl(request.getContextPath(), url);
    redirectUrl = response.encodeRedirectURL(redirectUrl);
    if (this.logger.isDebugEnabled()) {
      this.logger.debug("Redirecting to '" + redirectUrl + "'");
    }
    //    jsonException.jsonException(request, response, null,
    // HttpStatus.PERMANENT_REDIRECT.value());
    response.sendRedirect(redirectUrl);

    //    try {
    //      request.getRequestDispatcher(redirectUrl).forward(request, response);
    //    } catch (ServletException e) {
    //      e.printStackTrace();
    //      throw new IOException();
    //    }
  }

  protected String calculateRedirectUrl(String contextPath, String url) {
    if (!UrlUtils.isAbsoluteUrl(url)) {
      return this.isContextRelative() ? url : contextPath + url;
    } else if (!this.isContextRelative()) {
      return url;
    } else {
      url = url.substring(url.lastIndexOf("://") + 3);
      url = url.substring(url.indexOf(contextPath) + contextPath.length());
      if (url.length() > 1 && url.charAt(0) == '/') {
        url = url.substring(1);
      }

      return url;
    }
  }

  public void setContextRelative(boolean useRelativeContext) {
    this.contextRelative = useRelativeContext;
  }

  protected boolean isContextRelative() {
    return this.contextRelative;
  }
}
